﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BotonJXC.BLL;
using BotonJXC.Entity;
using BotonJXC.Util;

namespace BotonJXC.Forms
{
    public partial class OrdersForm : BaseMdiForm
    {

        public OrdersForm()
        {
            InitializeComponent();
        }
        private string[] type;
        private Int32 pageSize = 1;
        private Int32 totalSize;
        OrdersBLL ordersbll = new OrdersBLL();
        Orders Orders = null;
        ProductBLL ProductBLL = null;
        SupplierBLL SupplierBLL = null;
        private void OrdersForm_Load(object sender, EventArgs e)
        {
            InitForm();
            InitPaymets();
            InitWarehouses();
            InitUserDep();
            LoadDate();
  
        }
      
        /// <summary>
        /// 初始化数据
        /// </summary>
        public void LoadDate() {

          
            DateTime? startTime = null;
            DateTime? endTime = null;
            Orders orderSearch = new Orders();
            orderSearch.OrderType = this.type[1];
            PageModel<Orders> OrdersList = ordersbll.findOrdersByCondition(startTime, endTime, orderSearch, (pageSize - 1) * 1, 1);
            if (OrdersList.Results.Count == 0)
            {
                this.deletedBtn.Enabled = false;
                this.auditBtn.Enabled = false;
                this.saveBtn.Enabled = false;
            }
            else { 
               foreach(Orders Orders in OrdersList.Results ){
                 this.Orders = Orders;
               }
               this.OrderSnText.Text = this.Orders.OrderSn;
               this.PrintTimeText.Text = "打印次数: " + this.Orders.PrintTime;
               this.OrderTypeText.Text = "订单类型: " + StatusUtil.getOrdersTypeString(Int32.Parse(this.Orders.OrderType == null ? "1" : this.Orders.OrderType));
               this.AuditStatusText.Text = "单据状态: " + StatusUtil.getAuditString(Utils.ToInt(this.Orders.AuditStatus, 1));
               if (this.Orders.Supplier != null)
               {
                   this.SupplierCodeText.Text = this.Orders.Supplier.SupplierCode;
                   this.supplierNameText.Text = this.Orders.Supplier.SupplierName;
               }
               if (this.Orders.Ssupplier != null)
               {
                   this.SsupplierCodeText.Text = this.Orders.Ssupplier.SupplierCode;
                   this.ssupplierNameText.Text = this.Orders.Ssupplier.SupplierName;
               }

               this.UserDepCBox.Text = this.Orders.Department.DepName;
               this.WarehouseCBox.Text = this.Orders.BigWarehouse.Name;
              // UserWarehouseCBox.Items.Add(this.Orders.Warehouse.Name);
               this.SsupplierCodeText.Text = this.Orders.Ssupplier.SupplierCode;

               this.DeliveryDateTimePicker.Value = DateTime.Parse(this.Orders.DeliveryDate);
               this.PaymentCbox.Text = this.Orders.Payment.PaymentName;
               //this.WarehouseCBox.Text += this.Orders.;
               this.EffDayText.Text = this.Orders.EffDay.ToString();
               this.RemarkText.Text = this.Orders.Remark;
               this.AccountText.Text = "制单人: " + this.Orders.Account.Username;
               this.SalesmanText.Text = "业务员: " + this.Orders.Salesman;
               this.CreateTimeText.Text = "制单时间: " + string.Format("{0:yyyy/MM/dd HH:mm:ss}", this.Orders.CreateTime);
               this.AuditAccountText.Text = "审核人: " +( this.Orders.AuditAccount == null ? "" : this.Orders.AuditAccount.Username);
               this.AuditTimeText.Text ="审核时间: "+ string.Format("{0:yyyy/MM/dd HH:mm:ss}", this.Orders.AuditTime);
                //清空dateGridView
               ProductsDataGridViewOrders.Rows.Clear();
               foreach (OrderProducts OrderProducts in this.Orders.ProductsList) {
                   int index = this.ProductsDataGridViewOrders.Rows.Add();
                   this.ProductsDataGridViewOrders.Rows[index].Cells["ProductId"].Value = OrderProducts.Product.ProductId;
                   this.ProductsDataGridViewOrders.Rows[index].Cells["ProductCode"].Value = OrderProducts.Product.ProductCode;
                   this.ProductsDataGridViewOrders.Rows[index].Cells["Barcode"].Value = OrderProducts.Product.Barcode;
                   this.ProductsDataGridViewOrders.Rows[index].Cells["ProductName"].Value = OrderProducts.Product.ProductName;
                   this.ProductsDataGridViewOrders.Rows[index].Cells["UnitName"].Value = OrderProducts.Product.Unit == null ? "" : OrderProducts.Product.Unit.UnitName;
                   this.ProductsDataGridViewOrders.Rows[index].Cells["PackSpec"].Value = OrderProducts.Product.PackSpec;

                   this.ProductsDataGridViewOrders.Rows[index].Cells["inPurPrice"].Value = OrderProducts.Product.ProductCode;//含税进价

                   this.ProductsDataGridViewOrders.Rows[index].Cells["PurPrice"].Value = OrderProducts.Product.PurPrice; //未税进价

                   this.ProductsDataGridViewOrders.Rows[index].Cells["moneyColumn"].Value = "";//售价
                   this.ProductsDataGridViewOrders.Rows[index].Cells["totalMoneyColumn"].Value = "";//售价金额

                   this.ProductsDataGridViewOrders.Rows[index].Cells["TaxRate"].Value = OrderProducts.Product.TaxRate;//税率

                   this.ProductsDataGridViewOrders.Rows[index].Cells["packages"].Value = OrderProducts.Quantity;//件数
                   this.ProductsDataGridViewOrders.Rows[index].Cells["outMoneyColumn"].Value = OrderProducts.Product.ProductCode;//配送出库价
                   
                   this.ProductsDataGridViewOrders.Rows[index].Cells["Quantity"].Value = OrderProducts.Quantity;//订货数量
                   this.ProductsDataGridViewOrders.Rows[index].Cells["AllocateAddRate"].Value = OrderProducts.Product.AllocateAddRate; //配送加价率
                   this.ProductsDataGridViewOrders.Rows[index].Cells["DefPurPrice"].Value = OrderProducts.Product.DefPurPrice; //默认进价
                   if (OrderProducts.Product.Enabled != null) { 
                   this.ProductsDataGridViewOrders.Rows[index].Cells["ProductEnabled"].Value = OrderProducts.Product.Enabled.Equals("Y") ? "启用" : "停用";//标志
                   }
                   this.ProductsDataGridViewOrders.Rows[index].Cells["StockUpp"].Value = OrderProducts.Product.StockUpp;//库存上线
                   this.ProductsDataGridViewOrders.Rows[index].Cells["StockLow"].Value = OrderProducts.Product.StockLow;//库存下线

                   this.ProductsDataGridViewOrders.Rows[index].Cells["daySalesColumn"].Value = "//日销量";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["weekSalesColumn"].Value = "周销量";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["twoweekSalesColumn"].Value = "第二周销量";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["threeweekSalesColumn"].Value = "第三周";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["fourweekSalesColumn"].Value = "第四";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["avgSalesColumn"].Value = "平均";


                   this.ProductsDataGridViewOrders.Rows[index].Cells["notInStock"].Value = "在途库存";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["InStock"].Value = "当前库存";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["dayNumColumn"].Value = "日出库量";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["weekNumColumn"].Value = "周出库量";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["twoWeekColumn"].Value = "第二周出库量";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["threeWeekColumn"].Value = "//第三周出库量";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["fourWeekColumn"].Value = "第四出库量";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["avgNumColumn"].Value = "//平均出库量";
                   this.ProductsDataGridViewOrders.Rows[index].Cells["stockNum"].Value = "配送中心库存";//

                   this.ProductsDataGridViewOrders.Rows[index].Cells["LogisticsModelId"].Value = OrderProducts.Product.LogisticsModel == null ? "" : OrderProducts.Product.LogisticsModel.LogisticsModelName;//物流模式

                   this.ProductsDataGridViewOrders.Rows[index].Cells["InputSeq"].Value = OrderProducts.InputSeq;//录入顺序
                   
               }
                

            }

            //分页
            this.totalSize = OrdersList.PageCount;
            if (pageSize == OrdersList.PageCount)
            {
                this.next.Enabled = false;
            }
            else {
                this.next.Enabled = true;
            }
            if (pageSize == 1)
            {
                this.up.Enabled = false;
            }
            else {
                this.up.Enabled = true;
            }
            if (this.Orders != null)
            {
                //审核状态 按钮禁用
                if (this.Orders.AuditStatus.Equals("2"))
                {
                    this.auditBtn.Enabled = false;
                    this.saveBtn.Enabled = false;
                    this.deletedBtn.Enabled = false;
                    this.deleteProductBtn.Enabled = false;
                }
                else
                {
                    this.auditBtn.Enabled = true;
                    this.saveBtn.Enabled = true;
                    this.deletedBtn.Enabled = true;
                    this.deleteProductBtn.Enabled = true;
                }
            }
           
        }
        /// <summary>
        /// 加载结算方式
        /// </summary>
        private void InitPaymets() { 
         
            PaymentBLL PaymentBLL = new PaymentBLL();
            IList<Payment> PaymentList = PaymentBLL.FindAll();
            PaymentCbox.DataSource = PaymentList;
            PaymentCbox.DisplayMember = "PaymentName";//显示字段
            PaymentCbox.ValueMember = "PaymentId";//id值
        }
        /// <summary>
        /// 加载库存地
        /// </summary>
        private void InitWarehouses(){
            WarehouseBLL WarehouseBLL = new WarehouseBLL();
            IList<Warehouse> WarehouseList = WarehouseBLL.FindBigWarehouses();
            WarehouseCBox.DataSource = WarehouseList;

            WarehouseCBox.DisplayMember = "Name";//显示字段
            WarehouseCBox.ValueMember = "WarehouseId";//id值

             IList<Warehouse> UserWarehouseList = WarehouseBLL.FindByUserAll();
             UserWarehouseCBox.DataSource = UserWarehouseList;
             UserWarehouseCBox.DisplayMember = "Name";//显示字段
             UserWarehouseCBox.ValueMember = "WarehouseId";//id值

        }
        /// <summary>
        /// 加载用户部门
        /// </summary>
        private void InitUserDep() {
            DepartmentBLL DepartmentBLL = new DepartmentBLL();
            IList<Department> DepartmentList = DepartmentBLL.FindAll();
            UserDepCBox.DataSource = DepartmentList;
            UserDepCBox.DisplayMember = "DepName";//显示字段
            UserDepCBox.ValueMember = "DepId";//id值
        }


        /// <summary>
        /// 初始化
        /// </summary>
        private void InitForm() {
            type = this.Tag.ToString().Split(',');
            if ("1".Equals(type[1])) {
                this.Text = "订单申请";

            } else if ("2".Equals(type[1]))
            {
                this.Text = "采购订单";
                supplierOrderInit();

            }
            else if ("3".Equals(type[1]))
            {
                this.Text = "供应商订单";
                supplierOrderInit();
            }
            else  if ("4".Equals(type[1])){

                this.Text = "采购订货单";
                //this.PrintTimeBtn.Visible = false;
                //this.addBtn.Visible = false;
                //this.deletedBtn.Visible = false;
                //this.searchBtn.Visible = false;
                //this.saveBtn.Visible = false;
                //this.addProductsBtn.Visible = false;
                //this.deleteProductBtn.Visible = false;
                //this.returnBtn.Visible = false;
                //this.cancelBtn.Visible = false;
                //this.flowBtn.Visible = false;
                supplierOrderInit();
            }
        }

        private void supplierOrderInit()
        {
            outMoneyColumn.Visible = true;
            dayNumColumn.Visible = true;
            weekNumColumn.Visible = true;
            twoWeekColumn.Visible = true;
            threeWeekColumn.Visible = true;
            fourWeekColumn.Visible = true;
            orderValidLabel.Visible = true;
            EffDayText.Visible = true;
            avgNumColumn.Visible = true;

            DefPurPrice.Visible = false;
            totalMoneyColumn.Visible = false;
            moneyColumn.Visible = false;
            daySalesColumn.Visible = false;
            weekSalesColumn.Visible = false;
            twoweekSalesColumn.Visible = false;
            threeweekSalesColumn.Visible = false;
            fourweekSalesColumn.Visible = false;
            avgSalesColumn.Visible = false;
            notInStock.Visible = false;
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void next_Click(object sender, EventArgs e)
        {
            pageSize = pageSize + 1;
            LoadDate();
        }
        /// <summary>
        /// 上一单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void up_Click(object sender, EventArgs e)
        {
            pageSize = pageSize - 1;
            LoadDate();
        }

        private void addBtn_Click(object sender, EventArgs e)
        {
            this.saveBtn.Tag = "add";
            this.deletedBtn.Enabled = false;
            this.saveBtn.Enabled = true;
            ProductsDataGridViewOrders.Rows.Clear();

            this.OrderSnText.Text = "";
            this.PrintTimeText.Text = "打印次数:";
            this.OrderTypeText.Text = "订单类型:";
            this.AuditStatusText.Text ="单据状态:" ;
            this.SupplierCodeText.Text = "";

            this.UserDepCBox.SelectedIndex = 0;
            this.UserWarehouseCBox.SelectedIndex = 0;
            this.WarehouseCBox.SelectedIndex = 0;
            this.PaymentCbox.SelectedIndex = 0;
 
            this.SsupplierCodeText.Text = "";

            this.DeliveryDateTimePicker.Value = DateTime.Now;
         
            //this.WarehouseCBox.Text += this.Orders.;
            this.EffDayText.Text = "";
            this.RemarkText.Text = "";
            this.AccountText.Text = "制单人:";
            this.SalesmanText.Text = "业务员:";
            this.CreateTimeText.Text ="制单时间:";
            this.AuditAccountText.Text = "审核人:";
            this.AuditTimeText.Text = "审核时间:";
            this.supplierNameText.Text = "";
            this.ssupplierNameText.Text = "";
        }
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbExport_Click(object sender, EventArgs e)
        {
            Orders.AuditStatus = "2";
            Orders.AuditTime = DateTime.Now;
            Orders.AuditAccount = LoginForm.Account;

           // Orders.AuditRemark = AuditRemarktb.Text;
           // Orders.Remark = Remarktb.Text;
            OrdersBLL obll = new OrdersBLL();
             bool result = false;
            if( Orders.OrderType.Equals("1") ){
               result= obll.updateOrders(Orders, GetOutStocks(Orders));
            }
            else if (Orders.OrderType.Equals("2"))
            {
                result = obll.updateOrders(Orders, getOrders());
            }
            else {
                result = obll.updateOrders(Orders, GetAcceptance());
            }
          
            if (result)
            {
                MessageBox.Show("审核成功！");
                LoadDate();
            }
            else
            {
                MessageBox.Show("审核失败！");
            }
        }


        private Orders getOrders(){
            Orders _Orders = new Orders();
         
            _Orders.OrderId = 0;
            _Orders.OrderType = "4";
            _Orders.CreatePlace = "3";
            _Orders.Account = LoginForm.Account;
            _Orders.CreateTime = DateTime.Now;
            _Orders.AuditStatus = Utils.ToString((Int32)Status.None);
    
            _Orders.SourceId = this.Orders.OrderId;
            _Orders.OrderSn =  new BillSNGenerator().GeneratorBillSn(BillType.Order, BillSource.Purchase, LoginForm.StoreId);

            _Orders.BigWarehouse = this.Orders.BigWarehouse;
            _Orders.DeliveryDate = this.Orders.DeliveryDate;
            _Orders.Department = this.Orders.Department;
            _Orders.EffDay = this.Orders.EffDay;
            _Orders.InStatus = this.Orders.InStatus;
            _Orders.InStocks = this.Orders.InStocks;
            _Orders.OrgDepId = LoginForm.DepId;
            _Orders.OrgId = LoginForm.StoreId;
            _Orders.OutStatus = this.Orders.OutStatus;
            _Orders.OutStocks = this.Orders.OutStocks;
            _Orders.Payment = this.Orders.Payment;

            _Orders.Ssupplier = this.Orders.Ssupplier;
            _Orders.Supplier = this.Orders.Supplier;
            _Orders.Warehouse = this.Orders.Warehouse;
            IList<OrderProducts> ProductsList = new List<OrderProducts>(); ;
            foreach (OrderProducts OrderProducts in this.Orders.ProductsList) {
                OrderProducts _OrderProducts = new OrderProducts();
                _OrderProducts.AllocateAddRate = OrderProducts.AllocateAddRate;
                _OrderProducts.Amount = OrderProducts.Amount;
                _OrderProducts.InputSeq = OrderProducts.InputSeq;


                _OrderProducts.Price = OrderProducts.Price;
                _OrderProducts.Product = OrderProducts.Product;
                _OrderProducts.Quantity = OrderProducts.Quantity;
                _OrderProducts.TaxRate = OrderProducts.TaxRate;
                
                ProductsList.Add(_OrderProducts);
            }
            _Orders.ProductsList = ProductsList;
            return _Orders;
        }
        /// <summary>
        /// 自动生成出库单
        /// </summary>
        /// <param name="Orders"></param>
        /// <returns></returns>
        private OutStocks GetOutStocks(Orders Orders)
        {
            OutStocks OutStocks = new OutStocks();
            //出库单
            OutStocks.OutType = "1";
            //配人分店
            OutStocks.InStore = LoginForm.Store;
            //配人库存地
            OutStocks.InWarehouse = Orders.Warehouse;
            //制单人
            OutStocks.Account = LoginForm.Account;
            //制单时间
            OutStocks.CreateTime = DateTime.Now;
            //关联订单
            OutStocks.Orders = Orders;
            //单据产生地和编号
            if (Orders.BigWarehouse.Name.Equals("配送中心"))
            {
                OutStocks.OutSn = new BillSNGenerator().GeneratorBillSn(BillType.OutStock, BillSource.DistributionCenter, LoginForm.StoreId);
                OutStocks.CreatePlace = "2";
            }
            else if (Orders.BigWarehouse.Name.Equals("加工间"))
            {
                OutStocks.OutSn = new BillSNGenerator().GeneratorBillSn(BillType.OutStock, BillSource.Process, LoginForm.StoreId);
                OutStocks.CreatePlace = "3";
            }
           
            //部门
            OutStocks.OrgDepId = 0;
            //订单
            OutStocks.OrgId = 0;
            //默认未审核
            OutStocks.AuditStatus = "1";

            OutStocks.Remark = "系统自动生成";
            OutStocks.EffDay = 7;
            //货品信息
            IList<OutStocksProducts> Products = new BindingList<OutStocksProducts>();
            Int32 InputSeq= 1;
            foreach (OrderProducts OrderProducts in Orders.ProductsList)
            {
                OutStocksProducts OutStocksProducts = new OutStocksProducts();
                
                OutStocksProducts.Product = OrderProducts.Product;
                OutStocksProducts.PlanQuantity = OrderProducts.Quantity;
                OutStocksProducts.InputSeq = InputSeq;
                InputSeq += 1;

                Products.Add(OutStocksProducts);
            }
            OutStocks.ProductsList = Products;

            return OutStocks;
        
        }
        /// <summary>
        /// 自动生成验收单
        /// </summary>
        private Acceptance GetAcceptance()
        {
            Acceptance Acceptance = new Acceptance();


            if ("2".Equals(type[1]) || "4".Equals(type[1]))
            {
                Acceptance.AcceptanceType = "2";     //单据产生地
                Acceptance.CreatePlace ="2";
            }
            else {
                Acceptance.AcceptanceType = "1";
                //单据产生地
                Acceptance.CreatePlace = type[0];
            }
         
       
   
            Acceptance.Warehouse = Orders.BigWarehouse;
            Acceptance.Department = Orders.Department;
            Acceptance.Orders = Orders;
    
            Acceptance.Supplier = Orders.Supplier;
            Acceptance.SSupplier = Orders.Ssupplier;
            //制单人
         
            Acceptance.Account = LoginForm.Account;
            //制单时间
            Acceptance.CreateTime = DateTime.Now;
            Acceptance.Payment = Orders.Payment;

            
            //审核默认状态
            Acceptance.AuditStatus = "1";

            //备注
            Acceptance.Remark = "系统自动生成";
 
            //门店
            Acceptance.OrgId = LoginForm.StoreId;
            //部门
            Acceptance.OrgDepId = LoginForm.DepId;
            //货品信息
            IList<AcceptanceProducts> oplist = new BindingList<AcceptanceProducts>();


            foreach (OrderProducts OrderProducts in Orders.ProductsList)
            {
                AcceptanceProducts AcceptanceProducts = new AcceptanceProducts();
                AcceptanceProducts.Quantity = OrderProducts.Quantity;
                AcceptanceProducts.Product = OrderProducts.Product;
                oplist.Add(AcceptanceProducts);
            }
            Acceptance.AcceptanceProductsList = oplist;
        
            return Acceptance;
        }
        /// <summary>
        /// 单据删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tsbSelected_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要删除当前订单吗？", "删除确认",
             MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                bool result = ordersbll.deleteOrders(Orders);
                if (result)
                {
                    MessageBox.Show("单据删除成功!");
                }
                else
                {
                    MessageBox.Show("单据删除失败!");
                }

            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 保存订单
        /// </summary>
        private void AddOrders()
        {
            Orders Orders= new Orders();;
            if (!"add".Equals(this.saveBtn.Tag))
            {
                Orders = this.Orders;
            }
            BillSNGenerator BillSNGenerator = new BillSNGenerator();

            ///配送地
            Orders.BigWarehouse = (Warehouse)this.WarehouseCBox.SelectedItem;
            //管理课
            Orders.Department = (Department)this.UserDepCBox.SelectedItem;
            //供应商
            if (Utils.ToInt(this.SupplierCodeText.Tag, 0) != 0)
            Orders.Supplier  = new Supplier (Utils.ToInt( this.SupplierCodeText.Tag, 0));
            if (Utils.ToInt(this.SsupplierCodeText.Tag, 0) != 0)
            Orders.Ssupplier = new Supplier(Utils.ToInt(this.SsupplierCodeText.Tag, 0));
            
            //存货地
            Orders.Warehouse = (Warehouse)this.UserWarehouseCBox.SelectedItem; 
            //辅助供应商
            Orders.Ssupplier = SupplierBLL.FindSupplier(this.SsupplierCodeText.Text);
            Orders.DeliveryDate = DeliveryDateTimePicker.Value.ToString();
            Orders.Remark = this.RemarkText.Text;
            Orders.Payment = (Payment)this.PaymentCbox.SelectedItem;

            if (!"1".Equals(type[1]))
            {
                Orders.EffDay = Utils.ToInt(EffDayText.Text, 7);
            }

            Orders.OrderType = type[1];
            //orders.AuditTime = null;
            if ("add".Equals(this.saveBtn.Tag))
            {
                Orders.Account = LoginForm.Account;
                Orders.CreateTime = DateTime.Now;
                Orders.AuditStatus = "1";
                Orders.OutStatus = "1";
                Orders.InStatus = "1";
                Orders.CreatePlace = type[0];
                Orders.OrgId = LoginForm.StoreId;
                Orders.OrgDepId = LoginForm.DepId;
              
                if ("2".Equals(type[1]) || "3".Equals(type[1]))
                {
                    ///订单编号
                    Orders.OrderSn = BillSNGenerator.GeneratorBillSn(BillType.Order, BillSource.DistributionCenter, LoginForm.StoreId);

                }
                else if ("1".Equals(type[1]))
                {
                    
                    Orders.OrderSn = BillSNGenerator.GeneratorBillSn(BillType.Order, BillSource.Store, LoginForm.StoreId);
                }
                else if ("4".Equals(type[1]))
                {

                    Orders.OrderSn = BillSNGenerator.GeneratorBillSn(BillType.Order, BillSource.Purchase , LoginForm.StoreId);
                }
                Orders.ProductsList = this.GetProductList(Orders);
                bool result = ordersbll.saveOrders(Orders);
                if (result)
                {
                    MessageBox.Show("单据添加成功!");
                    LoadDate();
                    this.saveBtn.Tag = "up";           
                    this.saveBtn.Enabled = true;
                }
                else
                {
                    MessageBox.Show("单据添加失败!");
                }
            }
            else
            {
            
                Orders.ProductsList = this.GetProductList(Orders);
                //修改
                Orders.Salesman = LoginForm.Account.Username;
                bool result = ordersbll.updateOrders(Orders);
                if (result)
                {
                    MessageBox.Show("单据修改成功!");
                }
                else
                {
                    MessageBox.Show("单据修改失败!");
                }
            }

        }

        private void saveBtn_Click(object sender, EventArgs e)
        {
            AddOrders();
        }

   
        /// <summary>
        /// 加载货品信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProductsDataGridViewOrders_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            
            string parameter = ProductsDataGridViewOrders.Columns[e.ColumnIndex].Name;
            if ("ProductCode".Equals(parameter) || "Barcode".Equals(parameter) || "ProductName".Equals(parameter))
            {
                string value = ProductsDataGridViewOrders.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null ? "" : ProductsDataGridViewOrders.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (!"".Equals(value))
                {
                    if (ProductBLL == null) ProductBLL = new ProductBLL();
                    Product Product = ProductBLL.FindProduct(parameter, value);
                    if (Product == null)
                    {
                        MessageBox.Show("没有对应的货品");
                        ProductsDataGridViewOrders.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    }
                    else
                    {
                        ProductsDataGridViewOrders["ProductId", e.RowIndex].Value = Product.ProductId;
                        ProductsDataGridViewOrders["ProductCode", e.RowIndex].Value = Product.ProductCode;
                        ProductsDataGridViewOrders["Barcode", e.RowIndex].Value = Product.Barcode;
                        ProductsDataGridViewOrders["ProductName", e.RowIndex].Value = Product.ProductName;
                        ProductsDataGridViewOrders["UnitName", e.RowIndex].Value = Product.Unit == null ? "" : Product.Unit.UnitName;
                        ProductsDataGridViewOrders["PackSpec", e.RowIndex].Value = Product.ProductSpec;

                        ProductsDataGridViewOrders["inPurPrice", e.RowIndex].Value =
                            Product.PurPrice * (1 + Product.TaxRate);//含税进价 = 未税进价*(1+税率)
                        ProductsDataGridViewOrders["PurPrice", e.RowIndex].Value = Product.PurPrice;//未税进价

                        ProductsDataGridViewOrders["AllocateAddRate", e.RowIndex].Value = Product.AllocateAddRate * 100 + "%";//配送加价率
                        ProductsDataGridViewOrders["StockUpp", e.RowIndex].Value = Product.StockUpp;//库存上限
                        ProductsDataGridViewOrders["StockLow", e.RowIndex].Value = Product.StockLow;//库存下限
                        ProductsDataGridViewOrders["LogisticsModelId", e.RowIndex].Value = Product.LogisticsModel == null ? "" : Product.LogisticsModel.LogisticsModelName;//物流模式
                        ProductsDataGridViewOrders["DefPurPrice", e.RowIndex].Value = Product.DefPurPrice;//默认进价
                        ProductsDataGridViewOrders["TaxRate", e.RowIndex].Value = Product.TaxRate;//税率
                        //标志
                        ProductsDataGridViewOrders["ProductEnabled", e.RowIndex].Value = Product.Enabled=="Y"?"启用":"停用";//标志
                        
                    }
                }
            }

            if ("Quantity".Equals(parameter) || "moneyColumn".Equals(parameter))
            {
                Int32 Quantity = Utils.ToInt(ProductsDataGridViewOrders["Quantity", e.RowIndex].Value, 0);
                Int32 moneyColumn = Utils.ToInt(ProductsDataGridViewOrders["moneyColumn", e.RowIndex].Value, 0);
                if (Quantity != 0 && moneyColumn != 0)
                {
                    ProductsDataGridViewOrders["totalMoneyColumn", e.RowIndex].Value = Quantity * moneyColumn;
                }
                if (Quantity != 0)
                {
                    Int32 PackSpec = Utils.ToInt(ProductsDataGridViewOrders["PackSpec", e.RowIndex].Value, 0);
                    if (PackSpec != 0)
                    {
                        ProductsDataGridViewOrders["packages", e.RowIndex].Value = Quantity;
                    }
                }


            }
        }

        public IList<OrderProducts> GetProductList(Orders Orders)
        {
            IList<OrderProducts> oplist = new  List<OrderProducts>();
            for (int i = 0; i < ProductsDataGridViewOrders.Rows.Count - 1; i++)//如果DataGridView中有空的数据，则提示数据输入不完整并退出添加，不包括标题行
            {
                OrderProducts OrderProducts = new OrderProducts();
                Product Product = new Product();
                Product.ProductId = Utils.ToInt(ProductsDataGridViewOrders["ProductId", i].Value, 0);
                OrderProducts.Product = Product;
                //if (Orders.OrderId!=null) {
                //    OrderProducts.Order = Orders;
                //}
                OrderProducts.AllocateAddRate = Utils.ToDouble ( ProductsDataGridViewOrders["AllocateAddRate", i].Value , 0);
                OrderProducts.InputSeq = i + 1;
                OrderProducts.TaxRate = Utils.ToDouble ( ProductsDataGridViewOrders["TaxRate", i].Value , 0);
                OrderProducts.Amount = Utils.ToDouble ( ProductsDataGridViewOrders["totalMoneyColumn", i].Value,0);
                OrderProducts.Quantity = Utils.ToDouble (ProductsDataGridViewOrders["Quantity", i].Value,0);
                OrderProducts.Price =Utils.ToDouble ( ProductsDataGridViewOrders["PurPrice", i].Value,0);
                oplist.Add(OrderProducts);
            }
            return oplist;
        }
        /// <summary>
        /// 删除货品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteProductBtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要删除该行数据吗？", "删除确认",
                MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 确定 删除
                foreach (DataGridViewRow r in ProductsDataGridViewOrders.SelectedRows)
                {
                    if (!r.IsNewRow)
                    {
                        ProductsDataGridViewOrders.Rows.Remove(r);
                    }
                }
            }
           
        }

        private void SupplierCodeText_Leave(object sender, EventArgs e)
        {
            if (Utils.IsNotBlank(this.SupplierCodeText.Text))
            {
                if (SupplierBLL == null) SupplierBLL = new SupplierBLL();
                Supplier Supplier = SupplierBLL.FindSupplier(this.SupplierCodeText.Text);
                if (Supplier == null)
                {
                    MessageBox.Show("没有对应的供应商信息");
                    this.SupplierCodeText.Text = "";
                    this.SupplierCodeText.Tag = "";
                    this.supplierNameText.Text = "";
                }
                else
                {
                    this.SupplierCodeText.Tag = Supplier.SupplierId;
                    this.supplierNameText.Text = Supplier.SupplierName;
                }
            }
        }

        private void SsupplierCodeText_Leave(object sender, EventArgs e)
        {
            if (Utils.IsNotBlank(this.SsupplierCodeText.Text))
            {
                if (SupplierBLL == null) SupplierBLL = new SupplierBLL();
                Supplier Supplier = SupplierBLL.FindSupplier(this.SsupplierCodeText.Text);
                if (Supplier == null)
                {
                    MessageBox.Show("没有对应的供应商信息");
                    this.SsupplierCodeText.Tag = "";
                    this.SsupplierCodeText.Text = "";
                    this.ssupplierNameText.Text = "";
                }
                else
                {
                    this.SsupplierCodeText.Tag = Supplier.SupplierId;
                    this.ssupplierNameText.Text = Supplier.SupplierName;
                }
            }
        }
    }
}
